package com.gxa.www.cl.service.impl;

import com.gxa.www.cl.domain.entity.Supplier;
import com.gxa.www.cl.mapper.SupplierMapper;
import com.gxa.www.cl.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class SupplierServiceImpl implements SupplierService {

    private static final Logger logger = LoggerFactory.getLogger(SupplierServiceImpl.class);

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public List<Map<String, Object>> getSuppliers() {
        return supplierMapper.getSuppliers();
    }

    @Override
    public void deleteSupplier(Long id) {
        supplierMapper.deleteSupplier(id);
    }

    @Override
    @Transactional // 确保方法在事务中执行
    public int addSupplier(Map<String, Object> formData) {
        Supplier supplier = new Supplier();
        supplier.setMingcheng((String) formData.get("mingcheng"));
        supplier.setDizhi((String) formData.get("dizhi"));
        supplier.setLianxiren((String) formData.get("lianxiren"));
        supplier.setDianhua((String) formData.get("dianhua"));
        supplier.setYoubian((String) formData.get("youbian"));
        supplier.setChuanzhen((String) formData.get("chuanzhen"));
        supplier.setYouxiang((String) formData.get("youxiang"));
        supplier.setStatus(formData.get("status") != null ? (Integer) formData.get("status") : 1);

        // 检查数据库中是否已经存在相同的数据
        Supplier existingSupplier = supplierMapper.selectSupplierByFields(supplier);
        if (existingSupplier != null) {
            logger.warn("Duplicate supplier data detected: {}", supplier);
            return 0; // 返回0表示未插入数据
        }

        try {
            int result = supplierMapper.insertSupplier(supplier);
            if (result > 0) {
                return result;
            } else {
                throw new RuntimeException("插入供应商失败");
            }
        } catch (Exception e) {
            logger.error("Error adding supplier: {}", supplier, e);
            throw e;
        }
    }
}